package cn.itcast.com.Thread;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
1. 用多线程代码来模拟，迅雷用3个线程下载100M资源的的过程。
 每个线程每次，一次下载1兆(M)资源，直到下载完毕，即剩余的待下载资源大小为0
 (用一个整数表示资源大小，每次个线程每次下载多少兆(M), 剩余待下载资源就减少多少兆(M)，
  模拟我们售票的代码实现，考虑多线程的数据安全问题)
 */
public class shop02 {
    public static void main(String[] args) {
        salepath2 salepath1 = new salepath2();
        Thread thread1 = new Thread(salepath1, "w1");
        Thread thread2 = new Thread(salepath1, "w2");
        Thread thread3 = new Thread(salepath1, "w3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class salepath2 implements Runnable {

    int shenyu = 100;
    int xiazai = 0;
    private Object lock = new Object();
    private Object otherlock = new Object();

    //lock机制的🔒对象
    private Lock lockobj = new ReentrantLock();

    @SneakyThrows
    @Override
    public void run() {
        while (shenyu > 0) {
            //售票延迟
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock) {
                if (shenyu > 0) {
                    xiazai = xiazai + 1;
                    shenyu = shenyu - 1;
                    System.out.println(Thread.currentThread().getName() + ": 已经下载了" + xiazai + "M" + "还剩下"+shenyu+"M没有下载");
                }
            }

        }
    }

}